package com.soso.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.soso.dao.RolesDao;
import com.soso.entity.Roles;
import com.soso.entity.RolesSercher;
import com.soso.service.RolesService;
@Service
public class RolesServiceImpl implements RolesService{
    @Autowired
    RolesDao rd;
   
   
    
	@Override
	public Page<Roles> findpage(RolesSercher rs,Integer page, Integer limit) {
		Specification<Roles> spec=getSecher(rs);
		if(page==null)page=1;
		if(limit==null)limit=10;
		Pageable p=PageRequest.of(page-1, limit);
		return rd.findAll(spec,p);
	}
	private Specification<Roles> getSecher(RolesSercher rs) {
		return new Specification<Roles>() {

			@Override
			public Predicate toPredicate(Root<Roles> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				Predicate p=criteriaBuilder.conjunction();//动态 SQL 表达式
				List<Expression<Boolean>> list = p.getExpressions();
				if(!StringUtils.isEmpty(rs.getRname())) {
					list.add(criteriaBuilder.like(root.get("name"), "%"+rs.getRname()+"%"));
				}
				return p;
			}
			
		};
	}
	/*
	 * 修改与添加
	 * 
	 */
	@Override
	public Integer saveRoles(Roles r) {
		if(rd.saveAndFlush(r)!=null) {
			return 1;
		}
		return 0;
	}
	@Override
	public Integer deleroles(Roles ro) {
		try {
			rd.delete(ro);
			return 1;
		} catch (Exception e) {
			return 0;
		}
		
	}
	@Override
	public int adda(String Id, String name) {
		// TODO Auto-generated method stub
		return rd.adda(Id, name);
	}
	@Override
	public Integer deleteromoid(String aa) {
		// TODO Auto-generated method stub
		return rd.deleteromoid(aa);
	}
	@Override
	public Integer deletero(String bb) {
		// TODO Auto-generated method stub
		return rd.deletero(bb);
	
	}
	}
	
	
	


